package Z11_4_synchronizedControl;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author： pang-yun
 * @date： 2021-11-04 14:40
 * 功能目的 ：用于   reentrantLock 控制 顺序输出
 */

@Slf4j
public class ReentrantControl {
    static ReentrantLock lock = new ReentrantLock();
    static Condition ROOM = lock.newCondition();
    static boolean useFirst = false;

    public static void main(String[] args) {
        Thread first = new Thread(() -> {
            lock.lock();
            try {
                useFirst = true;
                log.info("first.....");
                ROOM.signalAll();
            } finally {
                lock.unlock();
            }
        }, "first");

        Thread second = new Thread(() -> {
            lock.lock();
            try {
               while (!useFirst){
                   ROOM.await();
                   log.info("need a break");
               }
               log.info("second....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "second");

        second.start();
        first.start();
    }
}
